package com.bdk.middle.cms.config;

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatConfig {

    @Value("${spring.tomcat.contextPath}")
    private String contextPath;

    @Value("${spring.tomcat.maxConnections}")
    private int maxConnections;

    @Value("${spring.tomcat.maxThreads}")
    private int maxThreads;

    @Value("${spring.tomcat.connectionTimeout}")
    private int connectionTimeout;

    @Value("${spring.tomcat.acceptCount}")
    private int acceptCount;

    @Value("${spring.tomcat.minSpareThreads}")
    private int minSpareThreads;

    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();
        tomcatFactory.addConnectorCustomizers(new MyTomcatConnectorCustomizer());
        //8-1 7-2 6-3 5-4 4-5
        tomcatFactory.setContextPath(contextPath);
        return tomcatFactory;
    }

    class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer {
        public void customize(Connector connector) {
            Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
            //设置最大连接数
            protocol.setMaxConnections(maxConnections);
            //设置最大线程数
            protocol.setMaxThreads(maxThreads);
            protocol.setConnectionTimeout(connectionTimeout);
            protocol.setAcceptCount(acceptCount);
            protocol.setMinSpareThreads(minSpareThreads);
        }
    }

}
